/*
 * @Author: xiaosihan
 * @Date: 2021-03-28 02:13:06
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2022-03-16 17:35:14
 */

import { isEmpty, isEqual, pick } from "lodash";
import { EventDispatcher } from "three";

// 全局公共方法
class Utils extends EventDispatcher {
    constructor() {
        super();
    }

    isProd = import.meta.env.MODE as string === "production";

    isDev = import.meta.env.MODE as string === "development";

    // 取随机数在某个范围里
    rand(start: number, end: number) {
        return Math.floor(Math.random() * (end - start + 1) + start);
    }

    /**
   * 多选文件
   */
    async selectFiles(accept = ".jpg,.jpeg,.png,.tga"): Promise<File[]> {
        return new Promise<File[]>((resolve, reject) => {
            const input = document.createElement("input");
            input.style.display = "none";
            input.type = "file";
            input.multiple = true;
            input.accept = accept;
            input.onchange = (e: any) => {
                const files = e.target.files as unknown as Promise<File[]>;
                resolve(files);
            }
            document.body.append(input);
            input.click();
            setTimeout(() => {
                input.remove();
            }, 100);
        });
    }

    /**
     * 单选文件
     */
    async selectFile(accept = ".jpg,.jpeg,.png,.tga"): Promise<File> {
        return new Promise<File>((resolve, reject) => {
            const input = document.createElement("input");
            input.style.display = "none";
            input.type = "file";
            input.multiple = false;
            input.accept = accept;
            input.onchange = (e: any) => {
                const files = e.target.files as PromiseLike<File>;
                resolve((files as unknown as File[])[0]);
            }
            document.body.append(input);
            input.click();
            setTimeout(() => {
                input.remove();
            }, 100);
        });
    }

    /**
     * 多选文件转blob
     */
    async selectFileToBlobs(accept = ".jpg,.jpeg,.png,.tga"): Promise<string[]> {
        const files = await this.selectFiles(accept) as File[];
        return files.map(file => window.URL.createObjectURL(file));
    }

    /**
     * 单选文件转blob
     */
    async selectFileToBlob(accept = ".jpg,.jpeg,.png,.tga"): Promise<string> {
        const files = await this.selectFile(accept) as File;
        return window.URL.createObjectURL(files);
    }

    /**
     * 比对指定字段是否相同
     */
    isEqualWidth(obj1: {}, obj2: {}, picks: Array<string> = []) {
        if (isEmpty(picks)) {
            return isEqual(obj1, obj2);
        }
        return isEqual(pick(obj1, picks), pick(obj2, picks));
    }

}

const utils = new Utils();

export default utils;